package org.i77soft.games.LGame.engine;

import java.util.HashMap;
import java.util.Iterator;

import android.view.KeyEvent;

public class Controller {

    public static final int BUTTON_UP = 0;
    public static final int BUTTON_LEFT = 1;
    public static final int BUTTON_RIGHT = 2;
    public static final int BUTTON_DOWN = 3;
    public static final int BUTTON_GRAB = 4;
    public static final int BUTTON_SUICIDE = 5;

    private boolean keys[];
    public boolean buttons[];
    private HashMap<Integer, Integer> buttonMap;

    public Controller() {
        keys = new boolean[256];
        buttons = new boolean[16];
        buttonMap = new HashMap<Integer, Integer>();
        bind(KeyEvent.KEYCODE_DPAD_UP, 0);
        bind(KeyEvent.KEYCODE_DPAD_LEFT, 1);
        bind(KeyEvent.KEYCODE_DPAD_RIGHT, 2);
        bind(KeyEvent.KEYCODE_DPAD_DOWN, 3);
        bind(KeyEvent.KEYCODE_SPACE, 4);
        bind(KeyEvent.KEYCODE_DPAD_CENTER, 5);
    }

    public void bind(int keyCode, int button) {
        if (keyCode >= 0 && keyCode < keys.length) {
            buttonMap.put(Integer.valueOf(keyCode), Integer.valueOf(button));
        }
    }

    @SuppressWarnings("unchecked")
    public void tick() {
        for (int i = 0; i < buttons.length; i++) {
            buttons[i] = false;
        }
        for (Iterator iterator = buttonMap.keySet().iterator(); iterator
                .hasNext();) {
            Integer key = (Integer) iterator.next();
            int button = ((Integer) buttonMap.get(key)).intValue();
            if (keys[key.intValue()]) {
                buttons[button] = true;
            }
        }
    }

    public void releaseAllKeys() {
        for (int i = 0; i < keys.length; i++) {
            keys[i] = false;
        }
    }

    public void keyPressed(int keyCode) {
        if (keyCode >= 0 && keyCode < keys.length) {
            keys[keyCode] = true;
        }
    }

    public void keyReleased(int keyCode) {
        if (keyCode >= 0 && keyCode < keys.length) {
            keys[keyCode] = false;
        }
    }

}
